//
//  SearchLocationViewController.m
//  u76ho
//
//  Created by m-air-01 on 16/1/12.
//  Copyright © 2016年 LV. All rights reserved.
//

#import "SearchLocationViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "LocationSearchTableViewCell.h"
#import "SendPictureViewController.h"

@interface SearchLocationViewController ()<UITableViewDataSource,UITableViewDelegate,AMapLocationManagerDelegate,AMapSearchDelegate>
{
    UITableView * _tableView;
    NSMutableArray * _dataSource;
    
    NSMutableArray * selectedArr;
    
    AMapSearchAPI * _search;
    NSString * city;
    UITextField * textField;
}

@property (nonatomic, strong) AMapLocationManager *locationManager;
@end

@implementation SearchLocationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self main];
    [self addItems];
    [self addNavgationBar];
    // Do any additional setup after loading the view.
}
-(void)main
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    //高德地图
    [AMapLocationServices sharedServices].apiKey = AMPKey;
    
    self.locationManager = [[AMapLocationManager alloc]init];
    self.locationManager.delegate = self;
    
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer];
    
    
    _dataSource = [[NSMutableArray alloc]init];
    selectedArr = [[NSMutableArray alloc]init];
    self.view.backgroundColor = [UIColor whiteColor];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [_tableView registerNib:[UINib nibWithNibName:@"LocationSearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"LocationSearchTableViewCell"];
    [self.view addSubview:_tableView];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    [AMapSearchServices sharedServices].apiKey = AMPKey;
    
    //初始化检索对象
    _search = [[AMapSearchAPI alloc]init];
    _search.delegate = self;
    
    
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == 2)
            {
                return;
            }
        }
        
        NSLog(@"**********location:%@", location);
        
        if (regeocode)
        {
            
            //            NSLog(@"reGeocode:%@", regeocode);
            
            NSLog(@"%@",regeocode.formattedAddress);
            city = regeocode.city;
        }
        
    }];

    

}
#pragma mark - _tableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSource.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * ID = @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.textLabel.text = _dataSource[indexPath.row];
    cell.textLabel.numberOfLines = 0;
    if ([selectedArr[indexPath.row] isEqualToString:@"1"]) {
        cell.textLabel.textColor = UIColorFromRGB(0x6EC844);
        UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
        imgV.image = [UIImage imageNamed:@"选中图标"];
        cell.accessoryView = imgV;
    }
    else
    {
        cell.textLabel.textColor = UIColorFromRGB(0x333944);
        cell.accessoryView = nil;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        int i = (int)indexPath.row;
        for (int j = 0; j<selectedArr.count; j++) {
            if (i == j) {
                [selectedArr replaceObjectAtIndex:j withObject:@"1"];
            }
            else
            {
                [selectedArr replaceObjectAtIndex:j withObject:@"0"];
            }
        }
        [_tableView reloadData];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"SearchLocationNoti" object:[_dataSource objectAtIndex:indexPath.row]];
    for (UIViewController *temp in self.navigationController.viewControllers) {
        if ([temp isKindOfClass:[SendPictureViewController class]]) {
            [self.navigationController popToViewController:temp animated:YES];
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

#pragma mark - addItems
-(void)addItems
{
    UIButton * cancleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancleBtn.frame = CGRectMake(0, 0, 60, 30);
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn addTarget:self action:@selector(backItem:) forControlEvents:UIControlEventTouchUpInside];
    [cancleBtn setTitleColor:UIColorFromRGB(0x333944) forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc]initWithCustomView:cancleBtn];
    self.navigationItem.rightBarButtonItem = leftItem;
}
-(void)backItem:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - NAVgationBarTitle
-(void)addNavgationBar
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 35)];
    view.backgroundColor = [UIColor lightGrayColor];
    view.layer.masksToBounds = YES;
    
    UIImageView * imgV = [[UIImageView alloc]initWithFrame:CGRectMake(SIZETO6W(15), (35-20)/2, 20, 20)];
    imgV.image = [UIImage imageNamed:@"搜索"];
    [view addSubview:imgV];
    
    textField = [[UITextField alloc]initWithFrame:CGRectMake(imgV.right + SIZETO6W(10), 0, view.frame.size.width-SIZETO6W(25)-20, 35)];
    [textField addTarget:self action:@selector(textChange:) forControlEvents:UIControlEventEditingChanged];
    textField.placeholder = @"搜索附近位置";
    [view addSubview:textField];
    
    view.layer.cornerRadius = 18;
    self.navigationItem.titleView = view;
}
-(void)textChange:(UITextField *)textField2
{
    if (![textField2.text isEqualToString:@""]) {
        //构造AMapInputTipsSearchRequest对象，设置请求参数
        AMapInputTipsSearchRequest *tipsRequest = [[AMapInputTipsSearchRequest alloc] init];
        tipsRequest.keywords = textField2.text;
        tipsRequest.city = city ? city : @"";
        //发起输入提示搜索
        [_search AMapInputTipsSearch: tipsRequest];
    }
}
//实现输入提示的回调函数
-(void)onInputTipsSearchDone:(AMapInputTipsSearchRequest*)request response:(AMapInputTipsSearchResponse *)response
{
    if(response.tips.count == 0)
    {
        return;
    }
    
    //通过AMapInputTipsSearchResponse对象处理搜索结果
    NSString *strCount = [NSString stringWithFormat:@"count: %ld", (long)response.count];
    NSString *strtips = @"";
    if (_dataSource.count!=0) {
        [_dataSource removeAllObjects];
        [selectedArr removeAllObjects];
    }
    for (AMapTip *p in response.tips) {
        strtips = [NSString stringWithFormat:@"%@\nTip: %@", strtips, p.description];
        NSString * str = [NSString stringWithFormat:@"%@%@",p.district,p.name];
        [_dataSource addObject:str];
        [selectedArr addObject:@"0"];
    }
    NSString *result = [NSString stringWithFormat:@"%@ \n %@", strCount, strtips];
    NSLog(@"InputTips: %@", result);
    [_tableView reloadData];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [textField resignFirstResponder];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
